package com.alks.function.service.impl.pcorder;

import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson2.JSON;
import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.dto.SysUserTokenDTO;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.service.RedisService;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.MinIoUtil;
import com.alks.common.utils.excelUtils.BizAssertUtils;
import com.alks.common.utils.excelUtils.ExcelPoiUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.common.utils.excelUtils.MergeUtil;
import com.alks.common.utils.stringUtils.ZStringUtils;
import com.alks.entity.data.entity.*;
import com.alks.entity.data.entity.dispatch.*;
import com.alks.entity.data.entity.excel.OrderProductTable;
import com.alks.entity.data.entity.excel.PcAggScheduleExcel;
import com.alks.entity.data.entity.excel.PcOrderHead2;
import com.alks.entity.data.enums.ResultCodeEnum;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.CollectionPointDto;
import com.alks.function.data.dto.PcAggScheduleDto;
import com.alks.function.data.dto.PcOrderHeadDto;
import com.alks.function.data.dto.pcfactoryquery.PartBfInDto;
import com.alks.function.data.dto.pcfactoryquery.PartBfOutDto;
import com.alks.function.data.dto.pcfactoryquery.PartStockHeadDto;
import com.alks.function.data.request.factoryquery.PartBfInRequest;
import com.alks.function.data.request.factoryquery.PartBfOutRequest;
import com.alks.function.data.request.factoryquery.PartStockRequest;
import com.alks.function.data.request.operate.material.MaterialDaI1Request;
import com.alks.function.data.request.order.*;
import com.alks.function.data.request.stock.PcOrderMaterialOrderDetailRequest;
import com.alks.function.data.request.yield.CollectionPointRequest;
import com.alks.function.mapper.MaterialMapper;
import com.alks.function.mapper.PcOrderHeadMapping;
import com.alks.function.mapper.PcProdStatusMapper;
import com.alks.function.mapper.SdUserMapper;
import com.alks.function.mapper.chengKong.PcLotHeadMapper;
import com.alks.function.service.OrderAsyncService;
import com.alks.function.service.PcOrderHeadService;
import com.alks.function.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import static com.alks.entity.data.enums.RedisFormatEnum.PUT_MTL_LENGTH;

/**
 * @author:xxxxx
 * @create: 2023-06-26 14:38
 * @Description: 订单
 */
@Service
@Slf4j
public class PcOrderHeadServiceImpl extends ServiceImpl<PcOrderHeadMapping, PcOrderHead> implements PcOrderHeadService {
    @Autowired
    PcOrderHeadMapping pcOrderHeadMapping;
    @Autowired
    RedisService redisService;
    @Value("${file.path}")
    private String file;

    @Override
    public ResponseInfo listOrder(PcOrderListRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        String key = request.toString();
        Set set = redisService.scan(key);
        PcOrderHeadDto headDto = null;
        if (set.size() == 1) {
            String head = redisService.get(key);
            headDto = JSON.parseObject(head, PcOrderHeadDto.class);
        }
        if (headDto != null) {
            return ResponseInfo.ok(headDto);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        List<PcOrderDetail> pcOrderDetails = pcOrderHeadMapping.orderList(request);
        PcOrderHeadDto dto = new PcOrderHeadDto();
        dto.setList(pcOrderDetails);
        BigDecimal num = pcOrderHeadMapping.countOrderNum(request);
        Long total = pcOrderHeadMapping.getOrderTotalSize(request);
        dto.setTotal(total);
        dto.setTotalNum(num);
        if (request.getPageNum() == 1) {
            redisService.set(key, JSON.toJSONString(dto));
        }
        return ResponseInfo.ok(dto);
    }

    @Override
    public ResponseInfo pcAggScheduleList(PcAggScheduleRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<PcAggSchedule> pcAggSchedules = pcOrderHeadMapping.pcAggSchList(request);
        PcAggScheduleDto dto = new PcAggScheduleDto();
        dto.setLists(pcAggSchedules);
        BigDecimal totalOrders = pcOrderHeadMapping.getTotalOrders(request);
        BigDecimal totalDays = pcOrderHeadMapping.getTotalDays(request);
        Long total = pcOrderHeadMapping.getAggSchTotalSize(request);
        dto.setTotal(total);
        dto.setTotalOrders(totalOrders);
        dto.setTotalDays(totalDays);
        return ResponseInfo.ok(dto);
    }

    // 获取查询条件
    @Override
    public ResponseInfo getOrderCondition() {
        OrderCondition orderCondition = new OrderCondition();
        orderCondition.setBrands(pcOrderHeadMapping.getOrderBrand());
        orderCondition.setSamples(pcOrderHeadMapping.getOrderSample());
        orderCondition.setSeasons(pcOrderHeadMapping.getOrderSeason());
        return ResponseInfo.ok(orderCondition);
    }
    //TODO 暂时不写
//    @Override
//    public ResponseInfo downloadPcOrderExcel() {
//        Date date = new Date();
//        String currentTime = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
//        String fileName = file+"\\订单汇总表_"+ currentTime+".xlsx";
//        WriteCellStyle contentCellStyle = new WriteCellStyle();
//        contentCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//
//        // 表头样式
//        WriteCellStyle headCellStyle = new WriteCellStyle();
//        headCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
//        headCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//        EasyExcel.write(fileName,PcOrderDetail.class)
//                .registerWriteHandler(new HorizontalCellStyleStrategy(headCellStyle, contentCellStyle))
//                .autoCloseStream(true)
//                .sheet()
//                .sheetName("订单汇总")
//                .doWrite(list); // 写入User数据到第一个sheet; // 写入Order数据到第二个sheet
////    }
//
////        EasyExcel.write(fileName, PcOrderDetail.class).sheet("订单").doWrite(list);
////        log.info(fileName);
//        return ResponseInfo.ok("下载成功");
//    }

    //采集节点查询
    @Autowired
    private OrderAsyncService orderAsyncService;

    @Override
    public ResponseInfo collectionPointList(CollectionPointRequest request) throws ExecutionException, InterruptedException {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        CollectionPointDto dto = new CollectionPointDto();
        List<CollectionPoint> list = pcOrderHeadMapping.collectionPointList(request);
        PageHelper.clearPage();
        Future<Long> total = orderAsyncService.getCollectionTotal(dto, request);
        Future<BigDecimal> orders = orderAsyncService.getCollectionOrders(dto, request);
        dto.setList(list);
        dto.setOrderTotals(orders.get());
        dto.setTotal(total.get());
        return ResponseInfo.ok(dto);
    }

    @Override
    public ResponseInfo getCollectionCondition() {
        Map<String, List<String>> map = new HashMap<>();
        List<String> brands = pcOrderHeadMapping.getCollectionBrands();
        List<String> seasons = pcOrderHeadMapping.getCollectionSeasons();
        List<String> samples = pcOrderHeadMapping.getCollectionSamples();
        map.put("brands", brands);
        map.put("seasons", seasons);
        map.put("samples", samples);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo pcAggScheduleCondition() {
        HashMap<String, List> map = new HashMap<>();
        List<String> list = pcOrderHeadMapping.pcAggScheduleCondition();
        map.put("style", list);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getPcOrderData(PcOrderDataRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        HashMap<String, Object> map = new HashMap<>();
        List<PcOrderDataRep> list = pcOrderHeadMapping.getPcOrderDataList(request);
        Long total = pcOrderHeadMapping.getPcOrderDataListTotal(request);
        changeColor(list);
        map.put("list", list);
        map.put("total", total);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getPcOrderShoePhotoFix(PcOrderShoePhotoFixRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        HashMap<String, Object> map = new HashMap<>();
        List<PcOrderShoePhotoFixRep> list = pcOrderHeadMapping.getPcOrderShoePhotoFix(request);
        for (PcOrderShoePhotoFixRep pcOrderShoePhotoFixRep : list) {
            if ("未检核".equals(pcOrderShoePhotoFixRep.getCfmFlag())) {
                pcOrderShoePhotoFixRep.setChange("Y");
            }
        }
        Long total = pcOrderHeadMapping.getPcOrderShoePhotoFixTotal(request);
        map.put("list", list);
        map.put("total", total);
        return ResponseInfo.ok(map);
    }

    //TODO 添加当前用户是否可以对该数据进行操作
    @Autowired
    SdUserMapper sdUserMapper;

    private void changeColor(List<PcOrderDataRep> list) {
        SysUserTokenDTO dto = UserIdThread.get();
        String deptNo = sdUserMapper.getDeptNo(dto.getLoginName());
        deptNo = deptNo == null ? "" : deptNo;
        for (PcOrderDataRep rep : list) {
            if (deptNo.equals(rep.getDeptNo())) {
                rep.setChange("Y");
            }
        }
    }

    //用于图片上传
    @Autowired
    MinIoUtil minIoUtil;
    @Autowired
    PcLotHeadMapper pcLotHeadMapper;

    //图片上传更新
    @Override
    public ResponseInfo updateShoePhoto(MultipartFile file, String style, String color) {
        UUID uuid = UUID.randomUUID();
        String photoPath = uuid.toString();
        photoPath = "/photo/profile/test/" + photoPath + ".jpg";
        //第一个参数为文件第二个参数为桶第三个是图片路径
        minIoUtil.upload(file, "photo", photoPath);
        pcLotHeadMapper.updatePhotoByStyleColor("http://192.168.1.220:9000/photo" + photoPath, style, color);
        return ResponseInfo.ok("上传成功");
    }

    @Override
    public ResponseInfo updatePcOrderData(PcOrderDateUpdate request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        for (PcOrderDataRep pcOrderDataRep : request.getList()) {
            if (pcOrderDataRep.getLotNo() == null || "".equals(pcOrderDataRep.getLotNo())) {
                return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
            }
        }
        pcOrderHeadMapping.updatePcOrderData(request.getList());
        return ResponseInfo.ok("修改成功");
    }

    @Override
    public ResponseInfo upDateShoeDetail(PcOrderShoePhotoFixRep request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getLotNo() == null || "".equals(request.getLotNo())) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        String lotNo = request.getLotNo();
        String[] split = lotNo.split("/");
        List<String> list = Arrays.asList(split);
        pcOrderHeadMapping.upDateShoeDetail(request, list);
        if (request.getCfmFlag() != null && !"".equals(request.getCfmFlag())) {
            pcOrderHeadMapping.updateShowCheck(request);
        }
        return ResponseInfo.ok("修改成功");
    }

    @Override
    public ResponseInfo updatePcOrderDataSac(PcOrderDataSacRequest request) {
        if (request == null || request.getList() == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        SysUserTokenDTO dto = UserIdThread.get();
        String name = dto.getUserName();
        request.setUsername(name);
        pcOrderHeadMapping.updatePcOrderDataSac(request);
        return ResponseInfo.ok("修改成功");
    }

    @Override
    public ResponseInfo getPcOrderDataRsjCondition() {
        HashMap<String, List<String>> map = new HashMap<>();
        List<String> brand = pcOrderHeadMapping.getOrderBrand();
        List<String> prodUserName = pcOrderHeadMapping.getProdUserName();
        map.put("brands", brand);
        map.put("prodUserName", prodUserName);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getPcOrderDataRsj(PcOrderDataRsjRequest request, String choose) {
        if ("1".equals(choose)) request.setProdUserName(UserIdThread.get().getUserName());
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        HashMap<String, Object> map = new HashMap<>();
        if ("1".equals(request.getFlag())) request.setProdUserName(UserIdThread.get().getUserName());
        List<PcOrderDataRsjRep> list = pcOrderHeadMapping.getPcOrderDataRsj(request);
        Long inTotal = pcOrderHeadMapping.getPcOrderDataRsjInTotal(request);
        Long total = pcOrderHeadMapping.getPcOrderDataRsjTotal(request);
        map.put("list", list);
        map.put("total", total);
        map.put("inTotal", inTotal);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getPcOrderDataTbs(PcOrderDataTbsRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        HashMap<String, Object> map = new HashMap<>();
        List<PcOrderDataTbsRep> list = pcOrderHeadMapping.getPcOrderDataTbs(request);
        Long total = pcOrderHeadMapping.getPcOrderDataTbsTotal(request);
        map.put("list", list);
        map.put("total", total);
        return ResponseInfo.ok(map);
    }

    //出货扫描 选择出货
    @Override
    public ResponseInfo outPcOrderDataTbs(PcOrderDataInOutRequest request) {
        //查询成型完成的数据
        List<PcOrderProdStatus> prods = pcOrderHeadMapping.getProds(request.getList());
        //设置出货单号
        StringBuilder shipSlipNo = new StringBuilder("XYCH");
        String format = new SimpleDateFormat("yyyyMM").format(new Date());
        shipSlipNo.append(format);
        RedisAtomicInteger ato = new RedisAtomicInteger(shipSlipNo.toString(), redisService.getConnectionFactory());
        ato.incrementAndGet();
        int increment = ato.get();
        //设置出货单号数字长度
        String no = String.valueOf(increment);
        String setNo = setNo(no);
        shipSlipNo.append(setNo);
        String slipNo = shipSlipNo.toString();
        //获取用户名
        SysUserTokenDTO userTokenDTO = UserIdThread.get();
        String username = userTokenDTO.getLoginName();
        String name = userTokenDTO.getUserName();
        prods.forEach(pcOrderProdStatus -> {
            pcOrderProdStatus.setProdUser(username);
            pcOrderProdStatus.setProdUserName(name);
            pcOrderProdStatus.setProdStep("出货完成");
            pcOrderProdStatus.setShipSlipNo(slipNo);
            pcOrderProdStatus.setProdSeq(pcOrderProdStatus.getProdSeq().add(new BigDecimal("1")));
        });
        pcOrderHeadMapping.outPcOrderDataTbs(prods);
        return ResponseInfo.ok("出货成功");
    }

    private String setNo(String no) {
        switch (no.length()) {
            case 1:
                no = "000" + no;
                break;
            case 2:
                no = "00" + no;
                break;
            case 3:
                no = "0" + no;
                break;
            case 4:
                no = "" + no;
                break;
        }
        return no;
    }

    @Override
    public ResponseInfo PcOrderDataOutRecord(PcOrderDataTbsRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        HashMap<String, Object> map = new HashMap<>();
        SysUserTokenDTO userTokenDTO = UserIdThread.get();
        String username = userTokenDTO.getLoginName();
        List<PcOrderDataOutRep> list = pcOrderHeadMapping.PcOrderDataOutRecord(request, username);
        Long total = pcOrderHeadMapping.PcOrderDataOutRecordTotal(request, username);
        map.put("list", list);
        map.put("total", total);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo pcOrderDataDeleteRecord(PcOrderDataInOutRequest request) {
        if (request.getList() == null) {
            return ResponseInfo.error("参数不能为空", 503);
        }
        pcOrderHeadMapping.deleteRecordByLots(request);
        return ResponseInfo.ok("删除成功");
    }

    @Override
    public ResponseInfo pcOrderDataSummaryAlsCondition() {
        Map<String, List<String>> map = new HashMap<>();
        List<String> samples = pcOrderHeadMapping.getPcOrderSummaryAlsSamples();
        List<String> brands = pcOrderHeadMapping.getPcOrderSummaryAlsBrands();
        List<String> seasons = pcOrderHeadMapping.getPcOrderSummaryAlsSeasons();
        map.put("samples", samples);
        map.put("brands", brands);
        map.put("seasons", seasons);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo pcOrderDataSummaryAls(PcOrderSummaryAnalysisRequest request) {
        Map<String, Object> map = new HashMap<>();
        LambdaQueryWrapper<SdUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SdUser::getChiName, request.getPerson());
        SdUser sdUser = sdUserMapper.selectOne(wrapper);
        if (sdUser != null) request.setPerson(sdUser.getUserId());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<PcOrderSummaryAnalysisRep> list = pcOrderHeadMapping.pcOrderDataSummaryAls(request);
        Integer total = pcOrderHeadMapping.pcOrderDataSummaryAlsTotal(request);
        BigDecimal orderSum = pcOrderHeadMapping.pcOrderDataSummaryAlsOrderSum(request);
        map.put("list", list);
        map.put("total", total);
        map.put("orderSum", orderSum);
        return ResponseInfo.ok(map);
    }

    @AutoPageAop
    @Override
    public ResponseInfo pcProductionDt(PcProductionDtRequest request) {
        Map<String, Object> map = new HashMap<>();
        List<PcProductionDtRep> list = pcOrderHeadMapping.pcProductionDt(request);
        map.put("list", list);
        Page<PcProductionDtRep> page = (Page<PcProductionDtRep>) list;
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }


    //修改生产动态表的计划日期和欠数
    @Autowired
    PcProdStatusMapper pcProdStatusMapper;

    @Override
    public ResponseInfo updatePcProductionDtPlanDate(PcProdStatus request) {
        LambdaQueryWrapper<PcProdStatus> wrapper = new LambdaQueryWrapper<PcProdStatus>()
                .eq(PcProdStatus::getLotNo, request.getLotNo());
        PcProdStatus update = pcProdStatusMapper.selectOne(wrapper);
        if (update == null) {
            return ResponseInfo.error("订单不存在");
        }
        //更新	纸板计划
        if (request.getDesignPlan() != null) {
            update.setDesignPlan(request.getDesignPlan());
        }
        //更新	材料计划
        if (request.getMtlPlan() != null) {
            update.setMtlPlan(request.getMtlPlan());
        }
        //更新	裁剪配套
        //欠数
        if (request.getCutShort() != null && request.getCutShort().compareTo(update.getOrderQty()) < 0) {
            update.setCutShort(request.getCutShort());
        } else if (request.getCutShort() != null && request.getCutShort().compareTo(update.getOrderQty()) > 0) {
            return ResponseInfo.error("裁剪配套欠数不能大于订单数量");
        }
        //计划
        if (request.getCutPlan() != null) {
            update.setCutPlan(request.getCutPlan());
        }
        //更新	工艺加工
        // 欠数
        if (request.getPrintShort() != null && request.getPrintShort().compareTo(update.getOrderQty()) < 0) {
            update.setPrintShort(request.getPrintShort());
        }
        // 计划
        if (request.getPrintPlan() != null) {
            update.setPrintPlan(request.getPrintPlan());
        }
        //更新	大底厂商
        // 欠数
        if (request.getEmbShort() != null && request.getEmbShort().compareTo(update.getOrderQty()) < 0) {
            update.setEmbShort(request.getEmbShort());
        } else if (request.getEmbShort() != null && request.getEmbShort().compareTo(update.getOrderQty()) > 0) {
            return ResponseInfo.error("大底欠数不能大于订单数量");
        }
        // 计划
        if (request.getEmbPlan() != null) {
            update.setEmbPlan(request.getEmbPlan());
        }
        //实际
        if (request.getEmbAct() != null) {
            update.setEmbAct(request.getEmbAct());
        }

        //更新	面衬
        // 欠数
        if (request.getHfShort() != null && request.getHfShort().compareTo(update.getOrderQty()) < 0) {
            update.setHfShort(request.getHfShort());
        } else if (request.getHfShort() != null && request.getHfShort().compareTo(update.getOrderQty()) > 0) {
            return ResponseInfo.error("面料欠数不能大于订单数量");
        }
        // 计划
        if (request.getHfPlan() != null) {
            update.setHfPlan(request.getHfPlan());
        }
        //实际
        if (request.getHfAct() != null) {
            update.setHfAct(request.getHfAct());
        }
        //更新	针车
        // 欠数
        if (request.getStitchShort() != null && request.getStitchShort().compareTo(update.getOrderQty()) < 0) {
            update.setStitchShort(request.getStitchShort());
        } else if (request.getStitchShort() != null && request.getStitchShort().compareTo(update.getOrderQty()) > 0) {
            return ResponseInfo.error("针织欠数不能大于订单数量");
        }
        // 计划
        if (request.getStitchPlan() != null) {
            update.setStitchPlan(request.getStitchPlan());
        }
        //更新	成型
        // 欠数
        if (request.getLastShort() != null && request.getLastShort().compareTo(update.getOrderQty()) < 0) {
            update.setLastShort(request.getLastShort());
        } else if (request.getLastShort() != null && request.getLastShort().compareTo(update.getOrderQty()) > 0) {
            return ResponseInfo.error("成型欠数不能大于订单数量");
        }
        // 计划
        if (request.getLastPlan() != null) {
            update.setLastPlan(request.getLastPlan());
        }

        System.out.println(update.getOrderQty());

        pcProdStatusMapper.update(update, wrapper);
        return ResponseInfo.ok("修改成功");
    }


    @Override
    public ResponseInfo updatePcProdMarkOk(String lotNo) {
        pcOrderHeadMapping.insertPcProdMarkOk(lotNo, UserIdThread.get().getCompanyId());
        return ResponseInfo.ok("标注成功");
    }

    @Override
    public ResponseInfo pcProductionDtMarkGet() {
        List<String> list = pcOrderHeadMapping.pcProductionDtMarkGet();
        return ResponseInfo.ok(list);
    }

    @Override
    public ResponseInfo updatePcProdCancelMarkOk(String lotNo) {
        pcOrderHeadMapping.deletePcProdCancelMarkOk(lotNo);
        return ResponseInfo.ok("取消标注成功");
    }

    @AutoPageAop
    @Override
    public ResponseInfo pcOrderStyleColorDd(PcOrderShoePhotoFixRequest request) {
        Map<String, Object> map = new HashMap<>();
        List<PcOrderStyleColorDdRep> list = pcOrderHeadMapping.pcOrderStyleColorDd(request);
        map.put("list", list);
        Page<PcOrderStyleColorDdRep> page = (Page<PcOrderStyleColorDdRep>) list;
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo pcOrderStyleColorDdCheck(PcOrderStyleColorDdCheckRequest request) {
        //查询pc_style_photo 没有数据则查询
        pcOrderHeadMapping.updatePcOrderStyleColorCheck(request);
        return ResponseInfo.ok("修改成功");
    }

    @Override
    public ResponseInfo pcOrderStyleColorDdDetail(String lotNo) {
        Map<String, Object> map = new HashMap<>();
        List<String> lots = new ArrayList<>();
        while (true) {
            int i = lotNo.indexOf("/");
            String s = "";
            if (i == -1) {
                s = lotNo;
                lotNo = "";
            } else {
                s = lotNo.substring(0, i);
            }
            lotNo = lotNo.substring(i + 1);
            if (s.contains("CK-WI")) {
                int index = lotNo.indexOf("/");
                String string = "";
                if (index == -1) {
                    string = lotNo;
                    lotNo = "";
                } else {
                    string = lotNo.substring(0, index);
                }
                string = "N-CK-WI/" + string;
                lotNo = lotNo.substring(index + 1);
                lots.add(string);
            } else {
                lots.add(s);
            }
            if (lotNo.isEmpty()) {
                break;
            }
        }
        List<PcOrderStyleColorDdDetailRep> list = pcOrderHeadMapping.pcOrderStyleColorDdDetail(lots);
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    @Override
    @Transactional
    public ResponseInfo updatePcOrderStyleColorDdDetail(PcOrderStyleColorDdDetailRep request) {
        pcOrderHeadMapping.updatePcOrderStyleColorDdDetail(request);
        pcOrderHeadMapping.updatePcYpLotHead(request.getLotNo(), request.getSampleType());
        return ResponseInfo.ok("修改成功");
    }

    @Override
    public ResponseInfo getPickingOperate(PcOrderPickingOperateRequest request) {
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        Map<String, Object> map = new HashMap<>();
        List<PcOrderPickingOperateRep> list = pcOrderHeadMapping.getPickingOperate(request);
        map.put("list", list);
        Integer total = pcOrderHeadMapping.getPickingOperateTotal(request);
        map.put("total", total);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getPickingOperateDetail(String lotNo) {
        Map<String, List<PcOrderPickingOperateDetailRep>> map = new HashMap<>();
        List<PcOrderPickingOperateDetailRep> list = pcOrderHeadMapping.getPickingOperateDetail(lotNo);
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo setTypeNameInPickingOperate(PcOrderCTN request) {
        List<PcOrderPickingOperateDetailRep> list = request.getPickingOperateDetailRepList();
        for (PcOrderPickingOperateDetailRep rep : list) {
            String mtlNo2 = pcOrderHeadMapping.getMtlTypeNo(rep);
            String mtlTypeNo = null;
            if (mtlNo2 != null) rep.setMtlTypeNo(mtlNo2.substring(0, 4));
            if (mtlNo2 == null) {
                if (rep.getMtlName().contains("+")) {
                    String[] split = rep.getMtlName().split("\\+");
                    for (String string : split) {
                        rep.setMtlName(string);
                        mtlTypeNo = pcOrderHeadMapping.getMtlTypeNoBy(rep);
                        if (mtlTypeNo != null) {
                            rep.setMtlTypeNo(mtlTypeNo);
                            break;
                        }
                    }
                } else {
                    mtlTypeNo = pcOrderHeadMapping.getMtlTypeNoBy(rep);
                    rep.setMtlTypeNo(mtlTypeNo);
                }
            }
        }
        pcOrderHeadMapping.setTypeNameInPickingOperate(request);
        return ResponseInfo.ok("生成完成");
    }

    @Autowired
    private MaterialMapper materialMapper;

    @Override
    public ResponseInfo setMtlNoInPickingOperate(PcOrderMtlNoPAndERequest request) {
        String userName = UserIdThread.get().getUserName();
        String lotNo = request.getLotNos().get(0);
        if (request.getCode().equals("0")) {
            List<PcOrderPickingOperateDetailRep> list = request.getList();
            pcOrderHeadMapping.setMtlNoEmptyPickingOperate(lotNo, list);
            return ResponseInfo.ok("置空成功");
        }
        for (PcOrderPickingOperateDetailRep rep : request.getList()) {
            PcOrderMaterToAllRep allRep = new PcOrderMaterToAllRep();
            allRep.setMtlName(rep.getMtlName());
            allRep.setMtlColor(rep.getMtlColor());
            allRep.setMtlSpec(rep.getMtlSpec());
            allRep.setMtlUnit(rep.getMtlUnit());
            String mtlNo = pcOrderHeadMapping.getMtlNo(allRep);
            if (mtlNo == null || mtlNo.isEmpty()) {
                String mtlTypeNo = rep.getMtlTypeNo();
                if (mtlTypeNo == null) {
                    //当前物料编码的前缀
                    String mtlNo2 = pcOrderHeadMapping.getMtlTypeNo(rep);
                    if (mtlNo2 != null) rep.setMtlTypeNo(mtlNo2.substring(0, 4));
                }
                mtlTypeNo = rep.getMtlTypeNo();
                if (mtlTypeNo == null) return ResponseInfo.error("请先分类辅助生成·或者设置分类名称");
                try {
                    //查询子物料编码的最大值
                    BigDecimal no2 = materialMapper.getMtlTypeNo2(mtlTypeNo);
                    BigDecimal add = no2.add(new BigDecimal(1));
                    int i = add.intValue();
                    String mtlNo1 = String.format("%0" + PUT_MTL_LENGTH.getValue() + "d", i);
                    mtlTypeNo = mtlTypeNo + mtlNo1;
                    pcOrderHeadMapping.updateCreateMtlNo1(mtlTypeNo, lotNo, rep);
                    //将该物料编码插入到 SD_MTL_NEW_KF
                    rep.setCompanyId(UserIdThread.get().getCompanyId());
                    materialMapper.insertSdMtlNewKf(mtlTypeNo, rep, userName);
                } catch (Exception e) {
                    return ResponseInfo.error("程序有点小问题、请稍后再试");
                }
            } else {
                pcOrderHeadMapping.setMtlNoProPickingOperate(lotNo, rep, mtlNo);
            }
        }
        return ResponseInfo.ok("生成成功");
    }

    @Override
    @Transactional
    public ResponseInfo setMtlNoCopyInLotNo(PcOrderMtlNoPAndERequest request) {
        SysUserTokenDTO dto = UserIdThread.get();
        String userName = dto.getUserName();
        List<PcOrderPickingOperateDetailRep> list = request.getList();
        if (request.getChoose() != null && "0".equals(request.getChoose())) {
            List<String> lotNos = request.getLotNos();
            list.forEach(x -> x.setCompanyId(dto.getCompanyId()));
            for (String lotNo : lotNos) {
                pcOrderHeadMapping.setMtlNoCopyInLotNoMtl(lotNo, list, userName);
            }
            return ResponseInfo.ok("添加成功");
        }
        if (request.getChoose() != null && "1".equals(request.getChoose())) {
            List<String> lotNos = request.getLotNos();
            if (request.getCheck() != null && "0".equals(request.getCheck())) {
                pcOrderHeadMapping.setPcOrderMtlCheck(lotNos, userName);
                return ResponseInfo.ok("修改成功");
            }
            if (request.getCheck() != null && "1".equals(request.getCheck())) {
                pcOrderHeadMapping.setPcOrderMtlUnCheck(lotNos, userName);
                return ResponseInfo.ok("修改成功");
            }
        }
        return ResponseInfo.error("接口调用失败请检查参数");
    }

    @Override
    public ResponseInfo pcOrderShielding(PcOrderShieldingRequest request) {
        //订单屏蔽
        SysUserTokenDTO dto = UserIdThread.get();
        if (request.getShield() != null && "0".equals(request.getShield())) {
            pcOrderHeadMapping.pcOrderShielding(request.getLots(), dto);
            return ResponseInfo.ok("订单已屏蔽");
        } else if (request.getShield() != null && "1".equals(request.getShield())) {
            pcOrderHeadMapping.deletePcOrderShielding(request.getLots());
            return ResponseInfo.ok("订单已取消屏蔽");
        }
        return ResponseInfo.error("请检查参数");
    }

    @Override
    public ResponseInfo pcOrderShieldingList(String lotNo, Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageSize == null) {
            pageNum = 1;
            pageSize = 10;
        }
        Map<String, Object> map = new HashMap<>();
        PageHelper.startPage(pageNum, pageSize, false);
        List<String> list = pcOrderHeadMapping.pcOrderShieldingList(lotNo);
        Integer total = pcOrderHeadMapping.pcOrderShieldingListTotal(lotNo);
        map.put("list", list);
        map.put("total", total);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo updatePickingOperate1(PcOrderPickingOperateDetailRep request) {

        String lotNo = request.getLotNo();
        if (lotNo == null || lotNo.isEmpty()) {
            return ResponseInfo.error("指令号不能为空");
        }
        int change = materialMapper.updatePickingOperate1(request);
        if (change <= 0) {
            return ResponseInfo.error("修改失败 请与开发人员联系");
        }
        return ResponseInfo.ok("修改成功");
    }

    @Override
    public ResponseInfo pcOrderMaterialDaI1(MaterialDaI1Request request) {
        //代表删除
        String lotNo = request.getLotNo();
        if (request.getChoose() != null && "1".equals(request.getChoose())) {
            List<PcOrderPickingOperateDetailRep> list = request.getRep();
            int i = materialMapper.deleteByList1(list, lotNo);
            if (i <= 0) {
                return ResponseInfo.error("删除失败、请与开发人员联系");
            }
            return ResponseInfo.ok("删除成功");
        } else if (request.getChoose() != null && "2".equals(request.getChoose())) {
            List<PcOrderPickingOperateDetailRep> rep1 = request.getRep();
            for (PcOrderPickingOperateDetailRep rep : rep1) {
                String userName = UserIdThread.get().getUserName();
                rep.setCompanyId(UserIdThread.get().getCompanyId());
                materialMapper.insertMaterial1(rep, lotNo, userName);
            }
            return ResponseInfo.ok("添加成功");
        }
        return ResponseInfo.error("参数不正确");
    }

    @Override
    @AutoPageAop
    public ResponseInfo outStockMessageList(PcOrderSummaryAnalysisRequest request) {
        Map<String, Object> map = new HashMap<>();
        List<OutStockDetailResp> list = pcOrderHeadMapping.outStockMessageList(request);
        BigDecimal prodTotal = pcOrderHeadMapping.getProdTotal(request);
        Page<OutStockDetailResp> page = (Page<OutStockDetailResp>) list;
        map.put("list", list);
        map.put("prodTotal", prodTotal);
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    @AutoPageAop
    public ResponseInfo mtlPurList(PcOrderMaterialOrderDetailRequest request) {
        Map<String, Object> map = new HashMap<>();
        List<PcOrderMaterialOrderDetailRep> list = materialMapper.pcOrderMtlMakeOrderDetail(request, "");
        BigDecimal qtyTotal = materialMapper.pcOrderMtlMakeOrderDetailQtyTotal(request, "");
        BigDecimal purQtyTotal = materialMapper.pcOrderMtlMakeOrderDetailPurQtyTotal(request, "");
        Integer total = materialMapper.pcOrderMtlMakeOrderDetailTotal(request, "");
        map.put("list", list);
        map.put("qtyTotal", qtyTotal);
        map.put("purQtyTotal", purQtyTotal);
        map.put("total", total);
        return ResponseInfo.ok(map);
    }

    @Override
    @AutoPageAop
    public ResponseInfo getPcSlipPart(PartBfInRequest request) {
        Map<String, Object> map = new HashMap<>();
        List<PartBfInDto> list = pcOrderHeadMapping.getPcSlipPart(request);
        Page<PartBfInDto> page = (Page<PartBfInDto>) list;
        map.put("list", list);
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @AutoPageAop
    @Override
    public ResponseInfo getOutPcSlipPart(PartBfOutRequest request) {
        List<PartBfOutDto> list = pcOrderHeadMapping.queryPartBfOut(request);
        Page<PartBfOutDto> page = (Page<PartBfOutDto>) list;
        /*封装输出*/
        Map map = new HashMap();
        map.put("total", page.getTotal());
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    @Override
    @AutoPageAop
    public ResponseInfo getStockPcSlipPart(PartStockRequest request) {
        List<PartStockHeadDto> list = pcOrderHeadMapping.queryPartBfStockHead(request);
        Page<PartStockHeadDto> page = (Page<PartStockHeadDto>) list;
        /*封装返回*/
        Map map = new HashMap();
        map.put("total", page.getTotal());
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getStockOutAndIn(String mtlNo) {
        Map<String, Object> map = new HashMap<>();
        List<PcSlipDetailPart> inList = pcOrderHeadMapping.getStockIn(mtlNo);
        List<PcSlipDetailPart> outList = pcOrderHeadMapping.getStockOut(mtlNo);
        map.put("inList", inList);
        map.put("outList", outList);
        return ResponseInfo.ok(map);
    }

    @Override
    public void downloadPcProductDt(HttpServletResponse response, PcProductionDtRequest request) throws IOException {
        List<OrderProductTable> list = pcOrderHeadMapping.downloadPcProductDt(request);
        Integer seq = 1;
        for (OrderProductTable table : list) {
            table.setSeqNo(seq++);
            if (table.getPhotoPath() != null) {
                try {
                    table.setPhoto(new URL(table.getPhotoPath()));
                } catch (IOException e) {
                    log.info("图片路径");
                }

            }
        }
        ExcelUtils.creatByTemplate(response, "生产动态表模板.xls", "生产动态表_" + DateUtils.dateTimeNow(), list);
    }

    @Override
    public void downloadMtlPurList(HttpServletResponse response, PcOrderMaterialOrderDetailRequest request) throws IOException {
        List<PcOrderMaterialOrderDetailRep> list = materialMapper.pcOrderMtlMakeOrderDetail(request, "");
        if ("0".equals(request.getChoose())) {
            ExcelUtils.creatByTemplate(response, "材料订购查询导出模板.xls", DateUtils.dateTimeNow(), list);
        } else if ("1".equals(request.getChoose())) {
            ExcelUtils.creatByTemplate(response, "大底订购查询导出模板.xls", DateUtils.dateTimeNow(), list);
        }

    }

    @Override
    public void downloadInSlipPart(HttpServletResponse response, PartBfInRequest request) throws IOException {
        InputStream stream = new ClassPathResource("templates/五金入库明细模板.xls").getStream();
        Map<String, Object> map = new HashMap<>();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = "五金出库明细_" + DateUtils.dateTimeNow() + ".xls";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        map.put("startDate", request.getSlipStartDate().format(formatter));
        map.put("endDate", request.getSlipEndDate().format(formatter));
        List<PartBfInDto> list = pcOrderHeadMapping.getPcSlipPart(request);
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置 垂直居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).excelType(ExcelTypeEnum.XLS).withTemplate(stream).
                registerWriteHandler(new MergeUtil(2, new int[]{0, 1})).registerWriteHandler(horizontalCellStyleStrategy).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        excelWriter.fill(map, writeSheet);
        excelWriter.fill(list, writeSheet);
        excelWriter.close();
    }

    @Override
    public void downloadOutPart(HttpServletResponse response, PartBfOutRequest request) throws IOException {
        InputStream stream = new ClassPathResource("templates/五金出库明细模板.xls").getStream();
        List<PartBfOutDto> list = pcOrderHeadMapping.queryPartBfOut(request);
        Map<String, Object> map = new HashMap<>();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = "五金出库明细_" + DateUtils.dateTimeNow() + ".xls";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        map.put("startDate", request.getSlipStartDate().format(formatter));
        map.put("endDate", request.getSlipEndDate().format(formatter));
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置 垂直居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).excelType(ExcelTypeEnum.XLS).withTemplate(stream).
                registerWriteHandler(new MergeUtil(2, new int[]{0, 1})).registerWriteHandler(horizontalCellStyleStrategy).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        excelWriter.fill(map, writeSheet);
        excelWriter.fill(list, writeSheet);
        excelWriter.close();

    }

    @Override
    public void downloadStockPart(HttpServletResponse response, PartStockRequest request) throws IOException {
        InputStream stream = new ClassPathResource("templates/五金库存表模板.xls").getStream();
        Map<String, String> map = new HashMap<>();
        map.put("date", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        List<PartStockHeadDto> list = pcOrderHeadMapping.queryPartBfStockHead(request);
        map.put("total", "0");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = "五金库存明细_" + DateUtils.dateTimeNow() + ".xls";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置 垂直居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).excelType(ExcelTypeEnum.XLS).withTemplate(stream).
                registerWriteHandler(new MergeUtil(2, new int[]{0})).registerWriteHandler(horizontalCellStyleStrategy).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        excelWriter.fill(map, writeSheet);
        excelWriter.fill(list, writeSheet);
        excelWriter.close();

    }

    @Override
    public void downloadPcAggSchedule(HttpServletResponse response) throws IOException {
        String fileName = "jdb_" + DateUtils.dateTimeNow();
        fileName = URLEncoder.encode(fileName, "UTF-8");
        List<PcAggScheduleExcel> list = pcLotHeadMapper.downloadPcAggSchedule();
        BigDecimal total = new BigDecimal(0);
        for (PcAggScheduleExcel x : list) {
            total = total.add(new BigDecimal(x.getOrderQty()));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("lineDate", new SimpleDateFormat("yyyyMMdd").format(new Date()));
        ExcelUtils.creatByTemplate(response, "总进度模板.xls", fileName, list, map);

    }

    @Override
    public ResponseInfo getProdUser(Integer choose) {
        Map<String, List<String>> map = new HashMap<>();
        map.put("prodName", pcOrderHeadMapping.getProdUser(choose));
        return ResponseInfo.ok(map);
    }

    @Override
    @Transactional
    public ResponseInfo uploadPcOrderHeadTemp(MultipartFile file) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
        String excelFileName = file.getOriginalFilename();
        int excelVersion = ExcelPoiUtils.getExcelVersion(excelFileName);
        Workbook workbook = null;
        List<PcOrderHead2> list = null;

        // 2003版本xls
        if (excelVersion == 1) {
            try {
                log.info("导入文件名:{},文件版本:2003", excelFileName);
                workbook = new HSSFWorkbook(file.getInputStream());
                list = readExcelValue(workbook);
                return getInfo(list, format);
            } catch (IOException e) {
                log.error("文件导入失败!");
                e.printStackTrace();
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        // 2007版本xlsx
        if (excelVersion == 2) {
            try {
                log.info("导入文件名:{},文件版本:2007", excelFileName);
                workbook = new XSSFWorkbook(file.getInputStream());
                list = readExcelValue(workbook);
                return getInfo(list, format);
                //写入pc_order_type
                //写入PC_YP_LOT_HEAD
            } catch (IOException e) {
                log.error("文件导入失败!");
                e.printStackTrace();
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    @Nullable
    private ResponseInfo<Object> getInfo(List<PcOrderHead2> list, SimpleDateFormat format) {
        if (list == null || list.isEmpty()) throw new ServiceErrorException("请检查文件");
        //写入pc_order_head
        for (int i = 0; i < list.size(); i++) {
            PcOrderHead2 pcOrderHead2 = list.get(i);
            byte[] photo = pcOrderHead2.getPhoto();
            String photoName = pcOrderHead2.getStyle() + pcOrderHead2.getColor() + ".jpg";
//            minIoUtil.upload(photo,"photo","/photo/profile/sdstylecolor"+photoName);
            if (!ZStringUtils.noeNotNull(pcOrderHead2)) continue;
            String style = pcOrderHead2.getStyle();
            String color = pcOrderHead2.getColor();
            String shoeName = pcOrderHead2.getShoeName();
            String brand = pcOrderHead2.getBrand();
            String custStyle = pcOrderHead2.getCustStyle();
            Integer len1 = pcOrderHead2.getBrand() == null ? 0 : pcOrderHead2.getBrand().length();
            Integer len2 = pcOrderHead2.getShoeName() == null ? 0 : pcOrderHead2.getShoeName().length();
            if (len1 > len2) {
                pcOrderHead2.setBrand(shoeName);
                pcOrderHead2.setShoeName(brand);
                pcOrderHead2.setCustStyle(style);
                pcOrderHead2.setStyle(custStyle);
            }
            if (pcOrderHead2.getBrand() == null || pcOrderHead2.getBrand().isEmpty() || pcOrderHead2.getSeasonType() == null || pcOrderHead2.getSeasonType().isEmpty()) {
                return ResponseInfo.error("品牌和季度不能为空");
            }
            String orderId = extracted(pcOrderHead2.getBrand(), pcOrderHead2.getSeasonType(), format, pcOrderHead2.getDeliveryDate() == null);
            pcOrderHead2.setOrderId(orderId);
            PcOrderHead pcOrderHead = new PcOrderHead();
            BeanUtils.copyProperties(pcOrderHead2, pcOrderHead);
            pcOrderHead.setSysUser(UserIdThread.get().getLoginName());
            pcOrderHead.setSysDate(LocalDateTime.now());
            Date deliveryDate = pcOrderHead2.getDeliveryDate();
            Instant instant = deliveryDate.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
            Date orderDate = pcOrderHead2.getOrderDate();
            LocalDateTime orderTime = orderDate.toInstant().atZone(zoneId).toLocalDateTime();
            pcOrderHead.setOrderDate(orderTime);
            pcOrderHead.setDeliveryDate(localDateTime);
            try {
                String sizeNo = pcOrderHead.getSizeNo();
                if (sizeNo.contains(".")) pcOrderHead.setSizeNo(sizeNo.substring(0, sizeNo.lastIndexOf(".")) + "#");
            } catch (Exception e) {

            }
            Integer countPcStyle = pcOrderHeadMapping.getPcSytyle(pcOrderHead);
            if (countPcStyle <= 0) pcOrderHeadMapping.insertToPcStyle(UserIdThread.get(), pcOrderHead);
            pcOrderHead.setCompanyId(UserIdThread.get().getCompanyId());
            boolean b = true;
            while (b){
            try {
                pcOrderHeadMapping.insert(pcOrderHead);
                b=false;
            }catch (Exception e){
                orderId = extracted(pcOrderHead2.getBrand(), pcOrderHead2.getSeasonType(), format, pcOrderHead2.getDeliveryDate() == null);
                pcOrderHead2.setOrderId(orderId);
                pcOrderHead.setOrderId(orderId);
            }
            }
            pcOrderHead2.setCompanyId(UserIdThread.get().getCompanyId());
            pcOrderHeadMapping.insertOrderType(pcOrderHead2);
            PcYpLotHead lotHead = new PcYpLotHead();
            BeanUtils.copyProperties(pcOrderHead2, lotHead);
            lotHead.setLotNo(orderId);
            lotHead.setStyleNo(pcOrderHead2.getStyle());
            lotHead.setStyleColor(pcOrderHead.getColor());
            lotHead.setDeliveryDate(pcOrderHead2.getDeliveryDate());
            lotHead.setCustomOrderDate(pcOrderHead2.getOrderDate());
            lotHead.setSeason(pcOrderHead2.getSeasonType());
            lotHead.setCustomStyle(pcOrderHead2.getCustStyle());
            lotHead.setOrderType(pcOrderHead2.getSampleType());
            lotHead.setCutTool(pcOrderHead.getStyle());
            String random = RandomStringUtils.random(10, false, true);
            lotHead.setUuid(random);
            pcOrderHeadMapping.insertIntoPcYpLotHead(lotHead);
        }
        return ResponseInfo.ok();
    }

    private List<PcOrderHead2> readExcelValue(Workbook workbook) throws ParseException {
        int totalRows = 0;
        int totalCells = 0;
        Sheet sheet = workbook.getSheetAt(0);
        // 得到表的总行数
        totalRows = sheet.getPhysicalNumberOfRows();
        // 根据第一行（标题行）获得总列数，获得总列数得根据某行确定
        if (totalRows >= 1 && sheet.getRow(0) != null) {
            totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
        List<PcOrderHead2> list = new ArrayList<>();
        // 逐行取数据，每行对应一条实体对象信息
        for (int rowNum = 1; rowNum < totalRows; rowNum++) {
            // 跳过标题行
            Row row = sheet.getRow(rowNum);
            if (row == null) {
                continue;
            }
            PcOrderHead2 vo = new PcOrderHead2();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            // 逐列取数据，每列对应一个实体对象属性
            for (int colNum = 0; colNum < totalCells; colNum++) {
                Cell cell = row.getCell(colNum);
                if (null != cell) {
                    switch (cell.getCellType()) {
                        case NUMERIC:
                            switch (colNum) {
                                case 13:
                                    vo.setOrderQty(new BigDecimal(cell.getNumericCellValue()));
                                    break;
                                case 17:
                                    vo.setRawMaterial(new BigDecimal(cell.getNumericCellValue()));
                                    break;
                                case 14:
                                    double value = cell.getNumericCellValue();
                                    long time = (long) ((value - 25569) * 86400 * 1000);
                                    Date deliveryDate = new Date(time);
                                    vo.setDeliveryDate(deliveryDate);
                                    break;
                                case 12:
                                    Double v = cell.getNumericCellValue();
                                    vo.setSizeNo(v.toString());
                                    break;
                                case 3:
                                    double orderValue = cell.getNumericCellValue();
                                    long orderTime = (long) ((orderValue - 25569) * 86400 * 1000);
                                    Date orderDate = new Date(orderTime);
                                    vo.setOrderDate(orderDate);
                                    break;
                                case 8:
                                    vo.setColor(String.valueOf(cell.getNumericCellValue()));
                                    break;
                            }
                            break;
                        case STRING:
                            switch (colNum) {
                                case 0:
                                    vo.setVendorNo(cell.getStringCellValue());
                                    break;
                                case 1:
                                    vo.setFactory(cell.getStringCellValue());
                                    break;
                                case 2:
                                    vo.setBrand(cell.getStringCellValue());
                                    break;
                                case 3:
                                    String value = cell.getStringCellValue();
                                    Date date = format.parse(value);
                                    vo.setOrderDate(date);
                                    break;
                                case 4:
                                    vo.setSeasonType(cell.getStringCellValue());
                                    break;
                                case 5:
                                    vo.setSampleType(cell.getStringCellValue());
                                    break;
                                case 6:
                                    vo.setCustStyle(cell.getStringCellValue());
                                    break;
                                case 7:
                                    vo.setStyle(cell.getStringCellValue());
                                    break;
                                case 8:
                                    vo.setColor(cell.getStringCellValue());
                                    break;
                                case 9:
                                    vo.setLastNo(cell.getStringCellValue());
                                    break;
                                case 10:
                                    vo.setMoldNo(cell.getStringCellValue());
                                    break;
                                case 11:
                                    vo.setSockNo(cell.getStringCellValue());
                                    break;
                                case 12:
                                    vo.setSizeNo(cell.getStringCellValue());
                                    break;
                                case 13:
                                    vo.setOrderQty(new BigDecimal(cell.getStringCellValue()));
                                    break;
                                case 14:
                                    try {
                                        vo.setDeliveryDate(format.parse(cell.getStringCellValue()));
                                    } catch (ParseException e) {
                                        vo.setDeliveryDate(dateFormat.parse(cell.getStringCellValue()));
                                    }
                                    break;
                                case 15:
                                    vo.setRemark(cell.getStringCellValue());
                                    break;
                                case 16:
                                    vo.setShoeName(cell.getStringCellValue());
                                    break;
                            }
                            break;
                        case BOOLEAN:
                            break;
                        case FORMULA:
                            if (colNum == 8) {

                            }
                            break;
                        case BLANK:
                            break;
                        default:
                            break;
                    }
                }
            }
            list.add(vo);
        }
        return list;
    }

    @Override
    @Transactional
    public ResponseInfo uploadPcBatchOrder(MultipartFile file) {
        Map<String, Object> data = new HashMap<>();
        String fileName = file.getOriginalFilename().toLowerCase();
        if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
            data.put("success", Boolean.valueOf(false));
            data.put("msg", "请上传Excel文件");
            throw new ServiceErrorException((String) data.get("msg"));
        }
        Map<String, Object> beans = new HashMap<>();
        List<OemLotHead> oemLotHeads = excelInput(file);
        beans.put("oemLotHeads", oemLotHeads);
        try {
//            JxlsExcelUtil.readExcel(file, "oem-lot-head", beans);
            if (oemLotHeads.size() == 0) {
                data.put("success", Boolean.valueOf(false));
                data.put("msg", "未找到需要导入任何记录");
                throw new ServiceErrorException((String) data.get("msg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            data.put("success", Boolean.valueOf(false));
            data.put("msg", "解析excel文件出错:" + e.getMessage());
            throw new ServiceErrorException((String) data.get("msg"));
        }
        try {
            addImport(oemLotHeads);
        } catch (Exception ex) {
            ex.printStackTrace();
            data.put("success", Boolean.valueOf(false));
            data.put("msg", ex.getMessage());
            throw new ServiceErrorException((String) data.get("msg"));
        }
        data.put("success", Boolean.valueOf(true));
        data.put("msg", "OEM业务数据导入成功");
        return ResponseInfo.ok(data);
    }

    @Override
    public ResponseInfo importMorePhotos(List<MultipartFile> list) {
        if (list == null) return ResponseInfo.error("不能上传空文件");
        List<String> lists = new ArrayList<>();
        for (MultipartFile multipartFile : list) {
            String filename = multipartFile.getOriginalFilename();
            String string = filename.substring(0, filename.lastIndexOf("."));
            String[] split = string.split("\\+");
            String style = null;
            String color = null;
            try {
                style = split[0];
                color = split[1];
            } catch (Exception e) {
                lists.add(string);
                continue;
            }
            String photoPath = "/photo/profile/pcstyle/" + filename;
            //第一个参数为文件第二个参数为桶第三个是图片路径
            minIoUtil.upload(multipartFile, "photo", photoPath);
            Integer i = pcLotHeadMapper.updatePhotoByStyleColor("http://192.168.1.220:9000/photo" + photoPath, style, color);
            if (i == 0) {
                lists.add(string);
            }
        }
        if (!lists.isEmpty()) return ResponseInfo.error("请检查" + lists + "的图片名称");
        return ResponseInfo.ok();
    }

    @Override
    public void downloadOrderDataSummaryAls(PcOrderSummaryAnalysisRequest request, HttpServletResponse response) throws IOException {
        LambdaQueryWrapper<SdUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SdUser::getChiName, request.getPerson());
        SdUser sdUser = sdUserMapper.selectOne(wrapper);
        if (sdUser != null) request.setPerson(sdUser.getUserId());
        List<PcOrderSummaryAnalysisRep> list = pcOrderHeadMapping.pcOrderDataSummaryAls(request);
        Integer seqNo = 1;
        Map<String, BigDecimal> map = new HashMap<>();
        BigDecimal orderTotal = new BigDecimal(0);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        for (PcOrderSummaryAnalysisRep rep : list) {
            Date date = rep.getOrderDate() == null ? new Date() : rep.getOrderDate();
            rep.setOrderTime(format.format(date));
            Date delivery = rep.getDeliveryDate() == null ? new Date() : rep.getDeliveryDate();
            rep.setDeliveryTime(format.format(delivery));
            Date prodTime = rep.getProdDate() == null ? new Date() : rep.getProdDate();
            rep.setProdTime(format.format(prodTime));
            rep.setSeqNo(seqNo++);
            orderTotal = orderTotal.add(rep.getOrderQty());
            try {
                rep.setUrl(new URL(rep.getPhotoPath()));
            } catch (MalformedURLException e) {
                log.info("路径不存在");
            }
        }
        map.put("total", orderTotal);
        ExcelUtils.creatByTemplate(response, "订单汇总表模板.xls", "订单汇总表_" + DateUtils.dateTimeNow(), list, map);
    }

    @Override
    public ResponseInfo updatePcOrderTable() {
        pcOrderHeadMapping.deleteProdStatus();
        pcOrderHeadMapping.updateProdStatus();
        return ResponseInfo.ok();
    }

    @Override
    @Transactional
    public ResponseInfo refreshOrderMaterialDaI2(List<String> lotNos) {
        int i = 0;
        List<String> lots = new ArrayList<>();
        List<String> lotError = new ArrayList<>();
        for (String lotNo : lotNos) {
            //查询型体跟颜色
            DevelopStyleColor style = pcOrderHeadMapping.getDevelopStyleColor(lotNo);
            style.setSysUser(UserIdThread.get().getUserName());
            Integer count = pcOrderHeadMapping.refreshOrderMaterialDaI2(style, lotNo);
            if (count > 0) {
                lots.add(lotNo);
            } else {
                lotError.add(lotNo);
            }
            //提取YF_BOM_PART_NEW2 中的材料到PC_ORDER_MTL中
        }
        return ResponseInfo.ok(lots.toString() + "指令添加成功," + lotError.toString() + "指令业务物料编码未添加");
    }

    @Override
    @Transactional
    public ResponseInfo setSampleTypeWithGeneration(PcOrderHead pcOrderHead) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
        //根据型体颜色查询yfstyle的基本信息存入pcOrderHead里面
        PcOrderHead head = pcOrderHeadMapping.getYfStyle(pcOrderHead);
        PcOrderHead head3 = pcOrderHeadMapping.getYfStyle2(pcOrderHead);
        if (head3 != null) return ResponseInfo.error("该订单已生成");
        if (head == null || head.getBrand() == null || head.getSeasonType() == null)
            return ResponseInfo.error("颜色品牌季度不能为空");
        if (head.getPhotoPath() == null || head.getPhotoPath().isEmpty()) return ResponseInfo.error("请先上传图片");
        head.setSysUser(UserIdThread.get().getLoginName());
        head.setSysDate(LocalDateTime.now());
        head.setOrderDate(LocalDateTime.now());
        head.setSampleType(pcOrderHead.getSampleType());
        head.setDeliveryDate(pcOrderHead.getDeliveryDate());
        head.setOrderQty(pcOrderHead.getOrderQty());
        head.setSizeNo(pcOrderHead.getSizeNo());
        head.setBomQty(pcOrderHead.getBomQty());
        head.setSockNo(pcOrderHead.getSockNo());
        head.setShoeName(pcOrderHead.getShoeName());
        //生成order_id
        String orderId = extracted(head.getBrand(), head.getSeasonType(), format, head.getDeliveryDate() == null);
        head.setOrderId(orderId);
        //添加到pc_order_head中
        //添加到pc_style 中
        Integer countPcStyle = pcOrderHeadMapping.getPcSytyle(head);
        if (countPcStyle <= 0) pcOrderHeadMapping.insertToPcStyle(UserIdThread.get(), head);
        head.setCompanyId(UserIdThread.get().getCompanyId());
        boolean flag = true;
        while (flag) {
            try {
                pcOrderHeadMapping.insert(head);
                flag = false;
            } catch (Exception e) {
                orderId = extracted(head.getBrand(), head.getSeasonType(), format, head.getDeliveryDate() == null);
                head.setOrderId(orderId);
            }
        }
        PcOrderHead2 head2 = new PcOrderHead2();
        BeanUtils.copyProperties(head, head2);
        pcOrderHeadMapping.insertOrderType(head2);
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo deletePcOrderHead(List<String> orderIds) {
        for (String orderId : orderIds) {
           Integer count = pcOrderHeadMapping.getProdByOrderId(orderId);
           if (count>0) return ResponseInfo.error("该订单已生成生产单，不能删除");
        }
        pcOrderHeadMapping.deletePcOrderHead(orderIds);
        pcOrderHeadMapping.deletePcOrderType(orderIds);
        return ResponseInfo.ok("删除成功");
    }

    @Override
    public ResponseInfo getBomByStyleColor(PcStyleCraftRep rep) {
        rep.setCompanyId(UserIdThread.get().getCompanyId());
        List<PcOrderHead> list = pcOrderHeadMapping.getBomByStyleColor(rep);
        return ResponseInfo.ok(list);
    }

    @Override
    public ResponseInfo getSampleType() {
        List<String> list = pcOrderHeadMapping.getSampleType();
        return ResponseInfo.ok(list);
    }

    private String extracted(String head, String head1, SimpleDateFormat format, boolean head2) {
        String orderId = "N-" + head + "-" + head1 + "-" + format.format(new Date());
        String key = "N-ORDER-ID"+format.format(new Date());
        Set scan = redisService.scan(key);
        RedisAtomicInteger ato = new RedisAtomicInteger(key, redisService.getConnectionFactory());
        if (scan.isEmpty()) {
            ato.set(1);
        } else {
            ato.getAndIncrement();
        }
        int i = ato.get();
        String s = String.format("%04d", i);
        orderId = orderId + s;
        if (head2) throw new ServiceErrorException("交货日期不能为空");
        return orderId;
    }

    private List<OemLotHead> excelInput(MultipartFile excelFile) {
        String excelFileName = excelFile.getOriginalFilename();
        int excelVersion = ExcelPoiUtils.getExcelVersion(excelFileName);
        Workbook workbook = null;
        List<OemLotHead> list = null;

        // 2003版本xls
        if (excelVersion == 1) {
            try {
                log.info("导入文件名:{},文件版本:2003", excelFileName);
                workbook = new HSSFWorkbook(excelFile.getInputStream());
                list = readExcelValue1(workbook);
                return list;
            } catch (IOException e) {
                log.error("文件导入失败!");
                e.printStackTrace();
            }
        }
        // 2007版本xlsx
        if (excelVersion == 2) {
            try {
                log.info("导入文件名:{},文件版本:2007", excelFileName);
                workbook = new XSSFWorkbook(excelFile.getInputStream());
                list = readExcelValue1(workbook);
                return list;
            } catch (IOException e) {
                log.error("文件导入失败!");
                e.printStackTrace();
            }
        }
        return null;
    }

    private List<OemLotHead> readExcelValue1(Workbook workbook) {
        int totalRows = 0;
        int totalCells = 0;
        Sheet sheet = workbook.getSheetAt(0);
        // 得到表的总行数
        totalRows = sheet.getPhysicalNumberOfRows();
        // 根据第一行（标题行）获得总列数，获得总列数得根据某行确定
        if (totalRows >= 1 && sheet.getRow(0) != null) {
            totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
        List<OemLotHead> list = new ArrayList<>();
        // 逐行取数据，每行对应一条实体对象信息
        for (int rowNum = 1; rowNum < totalRows; rowNum++) {
            // 跳过标题行
            Row row = sheet.getRow(rowNum);
            if (row == null) {
                continue;
            }
            OemLotHead vo = new OemLotHead();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            // 逐列取数据，每列对应一个实体对象属性
            for (int colNum = 0; colNum < totalCells; colNum++) {
                Cell cell = row.getCell(colNum);
                if (null != cell) {
                    Double value;
                    long time;
                    switch (cell.getCellType()) {
                        case NUMERIC:
                            switch (colNum) {
                                case 8:
                                    vo.setFactoryContractNo(String.valueOf(cell.getNumericCellValue()));
                                    break;
                                case 10:
                                    vo.setFactoryPrice(cell.getNumericCellValue());
                                    break;
                                case 13:
                                    vo.setCustPrice(cell.getNumericCellValue());
                                    break;
                                case 27:
                                    vo.setOrderQty((int) cell.getNumericCellValue());
                                    break;
                                case 28:
                                    value = cell.getNumericCellValue();
                                    time = (long) ((value - 25569) * 86400 * 1000);
                                    Date date = new Date(time);
                                    vo.setDeliveryDate(date);
                                    break;
                                case 2:
                                    value = cell.getNumericCellValue();
                                    time = (long) ((value - 25569) * 86400 * 1000);
                                    vo.setCustomOrderDate(new Date(time));
                                    break;
                                case 3:
                                    value = cell.getNumericCellValue();
                                    time = (long) ((value - 25569) * 86400 * 1000);
                                    vo.setPredicProdDate(new Date(time));
                                    break;
                                case 14:
                                    value = cell.getNumericCellValue();
                                    vo.setFactoryLotNo(String.valueOf(value.intValue()));
                                    break;

                            }
//                                // 定义日期格式正则表达式
//                                double value = cell.getNumericCellValue();
//                                long time = (long)((value - 25569)*86400*1000);
//                                Date date = new Date(time);
//                                vo.setOrderDate(date);

                            break;
                        case STRING:
                            switch (colNum) {
                                case 0:
                                    vo.setVendorAbbr(cell.getStringCellValue());
                                    break;
                                case 1:
                                    vo.setBrand(cell.getStringCellValue());
                                    break;
                                case 4:
                                    vo.setSeason(cell.getStringCellValue());
                                    break;
                                case 6:
                                    vo.setOrderType(cell.getStringCellValue());
                                    break;
                                case 8:
                                    vo.setFactoryContractNo(cell.getStringCellValue());
                                    break;
                                case 9:
                                    vo.setFactoryCur(cell.getStringCellValue());
                                    break;
                                case 11:
                                    vo.setCustomPiNo(cell.getStringCellValue());
                                    break;
                                case 12:
                                    vo.setCustCur(cell.getStringCellValue());
                                    break;
                                case 14:
                                    vo.setFactoryLotNo(cell.getStringCellValue());
                                    break;
                                case 15:
                                    vo.setStyleNo(cell.getStringCellValue());
                                    break;
                                case 16:
                                    vo.setStyleColor(cell.getStringCellValue());
                                    break;
                                case 22:
                                    boolean cut = "有".equals(cell.getStringCellValue());
                                    vo.setCutSample(cut);
                                    break;
                                case 23:
                                    boolean ant = "有".equals(cell.getStringCellValue());
                                    vo.setAntenatalSample(ant);
                                    break;
                                case 24:
                                    boolean tryOn = "有".equals(cell.getStringCellValue());
                                    vo.setTryOnSample(tryOn);
                                    break;
                                case 25:
                                    boolean test = "有".equals(cell.getStringCellValue());
                                    vo.setTestSample(test);
                                    break;
                                case 26:
                                    boolean cfs = "有".equals(cell.getStringCellValue());
                                    vo.setCfsSample(cfs);
                                    break;

                            }
                            break;
                        case BOOLEAN:
                            break;
                        case FORMULA:
                            break;
                        case BLANK:
                            break;
                        default:
                    }
                }
            }
            list.add(vo);
        }
        return list;
    }

    @Autowired
    SysUserService service;

    private void addImport(List<OemLotHead> oemLotHeads) {
        String companyId = UserIdThread.get().getCompanyId();
        VenType venType = new VenType();
        venType.setCompanyId("BF");
        venType.setTypeNo("G17");
        List<Vendor> vendors = materialMapper.selectByVenType(venType);
        if (vendors != null && vendors.size() != 0) {
            Date now = new Date();
            Map<String, Vendor> vendorsMap = new HashMap();
            vendors.forEach((vendorx) -> {
                vendorsMap.put(vendorx.getVendorAbbr(), vendorx);
            });
            Map<String, DevelopStyleColor> styleColorMap = new HashMap();
            Map<String, DevelopStyle> styleMap = new HashMap();
            Iterator var9 = oemLotHeads.iterator();
            int i = 1;
            while (var9.hasNext()) {
                OemLotHead oemLotHead = (OemLotHead) var9.next();
                if (ZStringUtils.isEmpty(oemLotHead.getVendorAbbr())) continue;
                oemLotHead.setCompanyId(companyId);
                Vendor vendor = (Vendor) vendorsMap.get(oemLotHead.getVendorAbbr());
                if (ZStringUtils.isNull(vendor)) {
                    throw new ServiceErrorException(ZStringUtils.format("存在无效的厂商【{}】", new Object[]{oemLotHead.getVendorAbbr()}));
                }
                if (ZStringUtils.isEmpty(oemLotHead.getFactoryContractNo())) {
                    throw new ServiceErrorException("单号[" + oemLotHead.getFactoryLotNo() + "]的工厂合同号不能为空!");
                }
                oemLotHead.setVendorNo(vendor.getVendorNo());
                if (ZStringUtils.isEmpty(oemLotHead.getFactoryContractNo()))
                    throw new ServiceErrorException("工厂指令不能为空");
                String styleColorKey = ZStringUtils.format("{}-{}", new Object[]{oemLotHead.getStyleNo(), oemLotHead.getStyleColor()});
                DevelopStyleColor styleColor = styleColorMap.get(styleColorKey);
                if (ZStringUtils.isNull(styleColor)) {
                    styleColor = new DevelopStyleColor();
                    styleColor.setCompanyId(companyId);
                    styleColor.setStyleNo(oemLotHead.getStyleNo());
                    styleColor.setStyleColor(oemLotHead.getStyleColor());
                    styleColor = pcOrderHeadMapping.selectColorByStyleColor(styleColor);
                    if (ZStringUtils.isNull(styleColor)) {
                        throw new ServiceErrorException(ZStringUtils.format("存在无效的型体配色资料，型体：【{}】，颜色：【{}】", new Object[]{oemLotHead.getStyleNo(), oemLotHead.getStyleColor()}));
                    }

                    styleColorMap.put(styleColorKey, styleColor);
                }
                DevelopStyle styleInfo = (DevelopStyle) styleMap.get(oemLotHead.getStyleNo());
                if (ZStringUtils.isNull(styleInfo)) {
                    styleInfo = new DevelopStyle();
                    styleInfo.setCompanyId(companyId);
                    styleInfo.setStyleNo(oemLotHead.getStyleNo());
                    styleInfo = pcOrderHeadMapping.selectByPrimaryKey(styleInfo);
                    if (ZStringUtils.isNull(styleInfo)) {
                        throw new ServiceErrorException(ZStringUtils.format("存在无效的型体资料，型体：【{}】", oemLotHead.getStyleNo()));
                    }

                    styleMap.put(oemLotHead.getStyleNo(), styleInfo);
                }
                oemLotHead.setBrand(ZStringUtils.isNull(styleInfo) ? "" : styleInfo.getCustNo());
                oemLotHead.setCreateDate(now);
                Integer userId = sdUserMapper.getUserIdByLogin(UserIdThread.get().getLoginName());
                oemLotHead.setCreateUserId(userId);
                oemLotHead.setCreateUserName(UserIdThread.get().getUserName());
                oemLotHead.setStyleName(styleInfo.getStyleName());
                oemLotHead.setCustName(styleInfo.getCustomName());
                if (ZStringUtils.isEmpty(oemLotHead.getCustCur())) {
                    oemLotHead.setCustCur("USD");
                }
                if (ZStringUtils.isEmpty(oemLotHead.getFactoryCur())) {
                    oemLotHead.setFactoryCur("RMB");
                }
                OemLotHead tempHead = pcLotHeadMapper.selectByFactoryLotNo(oemLotHead);
                if (ZStringUtils.isNotNull(tempHead)) {
                    oemLotHead.setUuid(tempHead.getUuid());
                    if (tempHead.isComplete()) {
                        throw new ServiceErrorException(ZStringUtils.format("工厂指令【{}】已结案,请勿重复导入！", new Object[]{oemLotHead.getFactoryLotNo()}));
                    }
                    int exportEditNum = pcOrderHeadMapping.selectExportCfmCount(UserIdThread.get().getCompanyId(), oemLotHead.getFactoryLotNo());
                    if (exportEditNum > 0) {
                        throw new ServiceErrorException(ZStringUtils.format("工厂指令【{}】存在船务信息,请核实", new Object[]{oemLotHead.getFactoryLotNo()}));
                    }
//                    if (ZStringUtils.isNotEmpty(pcOrderHeadMapping.selectByLotUUID(oemLotHead))) {
//                        throw new ServiceErrorException(ZStringUtils.format("存在重复的工厂指令【{}】", new Object[]{oemLotHead.getFactoryLotNo()}));
//                    }
                    pcLotHeadMapper.deleteByUUID(tempHead);
                    int payAOACfmCount = pcLotHeadMapper.selectPayCfmCount(UserIdThread.get().getCompanyId(), oemLotHead.getFactoryLotNo());
                    BizAssertUtils.isFalse(payAOACfmCount > 0, StringUtils.format("工厂指令【{}】已对账检核无法修改,请核实", new Object[]{oemLotHead.getFactoryLotNo()}));
                    int num = this.pcLotHeadMapper.selectCfmCount(UserIdThread.get().getCompanyId(), oemLotHead.getFactoryLotNo());
                    if (num > 0) {
                        oemLotHead.setFactoryPrice(tempHead.getFactoryPrice());
                        oemLotHead.setFactoryCur(tempHead.getFactoryCur());
                        oemLotHead.setCustPrice(tempHead.getCustPrice());
                        oemLotHead.setCustCur(tempHead.getCustCur());
                    } else {
                        oemLotHead.setFactoryPrice(oemLotHead.getFactoryPrice() == null ? tempHead.getFactoryPrice() : oemLotHead.getFactoryPrice());
                        oemLotHead.setFactoryCur(oemLotHead.getFactoryCur() == null ? tempHead.getFactoryCur() : oemLotHead.getFactoryCur());
                        oemLotHead.setCustPrice(oemLotHead.getCustPrice() == null ? tempHead.getCustPrice() : oemLotHead.getCustPrice());
                        oemLotHead.setCustCur(oemLotHead.getCustCur() == null ? tempHead.getCustCur() : oemLotHead.getCustCur());
                    }
                    oemLotHead.setCutSample(tempHead.isCutSample());
                    oemLotHead.setAntenatalSample(tempHead.isAntenatalSample());
                    oemLotHead.setTryOnSample(tempHead.isTryOnSample());
                    oemLotHead.setTestSample(tempHead.isTestSample());
                    oemLotHead.setCfsSample(tempHead.isCfsSample());
                    oemLotHead.setRawMaterial(tempHead.isRawMaterial());
                    oemLotHead.setShoelace(tempHead.isShoelace());
                    oemLotHead.setCutQty(tempHead.getCutQty());
                    oemLotHead.setCraftQty(tempHead.getCraftQty());
                    oemLotHead.setMatchQty(tempHead.getMatchQty());
                    oemLotHead.setStitchQty(tempHead.getStitchQty());
                    oemLotHead.setOutSoleQty(tempHead.getOutSoleQty());
                    oemLotHead.setInsoleQty(tempHead.getInsoleQty());
                    oemLotHead.setFinishQty(tempHead.getFinishQty());
                    oemLotHead.setRemark(tempHead.getRemark());
                    oemLotHead.setComplete(tempHead.isComplete());
                }
                SysOperLog param = new SysOperLog();
                String ip = UserIdThread.get().getLoginIp();
                param.setOperIp(ip);
                param.setMethod("量产订单导入");
                param.setBusinessType(6);
                param.setOperName(UserIdThread.get().getLoginName());
                param.setOperParam(com.alibaba.fastjson.JSON.toJSONString(oemLotHead));
                param.setOperTime(new Date());
                param.setTitle("量产订单导入");
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                oemLotHead.setUuid(uuid);
                pcLotHeadMapper.insertOperlog(param);
                pcOrderHeadMapping.insertOemLot(oemLotHead);
            }
        }
    }
}


